﻿using Bigway.Common.Models.DtoModels;
using FluentValidation;

namespace Bigway.Common.Validations;
using static Errors;

public static class ValidatorExtensions
{
    public static void SetApiKey(string apiKey)
    {
        ApiKey = apiKey;
    }

    public static string ApiKey { get; set; } = "";

    public static async Task<TResponse?> ValidateRequestAsync<TRequest, TResponse>(
        this IValidator<TRequest>? validator,
        string apiKey,
        TRequest request,
        CancellationToken token = default
    )
        where TResponse : BaseResponseDto, new()
    {
        if (apiKey != ApiKey)
            return Unauthorized<TResponse>();
        if (validator is null)
            return default;

        var result = await validator.ValidateAsync(request, token);
        if (result.IsValid) return default;
        var errors = result.Errors;
        var message = errors.Aggregate("",
            (e, error) => e + error.ErrorCode + " ").Trim();
        var userMessage = errors.Aggregate("",
            (e, error) => e + error.ErrorMessage + " ").Trim();
        return InvalidRequest<TResponse>(message, userMessage);
    }
}